<template>
	<div id="role">
		<!-- 输入框子 -->
		<el-row class="role-head">
			<el-input placeholder="请输入管理员ID" v-model="inpName"></el-input>
			<el-button type="primary" icon="el-icon-search" @click="searchUser">查询</el-button>
			<el-button type="primary" icon="el-icon-edit" @click="addUSer">添加</el-button>
			<el-button type="primary" icon="el-icon-bottom" @click="downLoadExsl">导出</el-button>
		</el-row>
		<template>
			<el-table :key="Math.random()" :data="tableData" style="width: 100%" border
				:header-cell-style="{textAlign: 'center'}" :cell-style="{textAlign:'center'}" id="out-table">
				<el-table-column label="管理员ID" prop="id" sortable>
				</el-table-column>
				<el-table-column label="管理员名称" prop="username">
				</el-table-column>
				<el-table-column label="头像" prop="avatar">
					<template slot-scope="slot">
						<img :src="slot.row.avatar" class="avator2" />
					</template>
				</el-table-column>
				<el-table-column label="管理员角色" prop="roleIds">
					<template slot-scope="slot" v-for="(item,index) in userList">
						 <!--  v-if="item2==item.id" -->
						<el-tag type="success"v-for="(item2,index) in slot.row.roleIds" v-if="item.id=item">
							<!-- {{item2}} -->
							{{item.name}}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column align="right" label="操作">

					<template slot-scope="scope">
						<el-button type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
						<el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</template>

		<template>
			<!-- 这里是分页功能 -->
				<div class="block">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page="page" :page-sizes="[10, 20, 30, 40]" :page-size="limit"
					layout="total, sizes, prev, pager, next, jumper" :total="total">
				</el-pagination>
			</div>
		</template>

		<template>
			<!-- 管理员的添加 -->
			<el-dialog :title="title" :visible.sync="dialogVisible" width="45%">
				<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm">
					<el-form-item label="管理员名称" :label-width="formLabelWidth" prop="userName">
						<el-input v-model="ruleForm.userName" autocomplete="off"></el-input>
					</el-form-item>
					<el-form-item label="管理员密码" :label-width="formLabelWidth" prop="password">
						<el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
					</el-form-item>
					<el-form-item label="管理员头像" :label-width="formLabelWidth">
						<el-upload :headers="tokens" class="avatar-uploader" action="http://192.168.1.54:8080/admin/storage/create" :show-file-list="false"
							:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
							:class="{hide:hideUpload}" :on-change="onChange2" :on-remove="handleRemove"
							:multiple='false' ref='upload'>
							<img v-if="imageUrl" :src="imageUrl" class="avatar">
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</el-form-item>
					<el-form-item label="管理员角色" :label-width="formLabelWidth">
						<el-select v-model="ruleForm.region" placeholder="请选择管理员" multiple filterable allow-create
							default-first-option>
							<el-option v-for="item in ruleForm.type" :key="item.id" :value="item.id" :label="item.name">
							</el-option>
						</el-select>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
					<el-button @click="dialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="submitForm(ruleForm)">确 定</el-button>
				</span>
			</el-dialog>

		</template>
		
	</div>

</template>

<script>
	import {
		adminList,
		allUser,
		addAdmin,
		upAdmin,
		delAdmin
	} from '../../https/system'
	import FileSaver from 'file-saver'
	import XLSX from 'xlsx'

	export default {
		data() {
			var validatePass = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入密码'));
				} else {

					callback();
				}
			};
			var validateName = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('账号不能为空'));
				} else {
					callback();
				}
			}
			return {
				// 专注修改的管理员id
				adminId:'',
				userList:[],
				hideUpload: false,
				limitCount: 1,
				// 输入框绑定显示的数据
				inpName: '',
				// 主要列表显示的数据
				tableData: [],
				// 当前默认选中哪个页面
				page: 1,
				// 每页的限制条数
				limit: 0,
				tokens: {
					"X-Litemall-Admin-Token": ''
				},
				// 总共条数
				total: 0,
				// 头像
				avatar: '',
				// 添加用户的弹窗
				dialogVisible: false,
				title:'',
				// 这里是表单的东西,
				formLabelWidth: '120px',
				ruleForm: {
					// 管理员名称
					userName: '',
					// 密码
					password: '',
					// 被选中的值
					region: '',
					delivery: false,
					// 子选项列表
					type: [],
					avatar: '',
				},
				// 表单验证的规则
				rules: {
					userName: [{
						validator: validateName,
						trigger: 'blur'
					}],
					password: [{
						validator: validatePass,
						trigger: 'blur'
					}]
				},
				
				// 图片的路径
				imageUrl: '',
				// 判断是编辑还是上传
				add:'',

			}
		},
		methods: {
			addUSer() {
				// 添加之前进行清空
				this.ruleForm.userName='',
				this.ruleForm.password='',
				this.ruleForm.region=''
				// 清空图片
				this.imageUrl=''
				this.title="添加用户"
				// 添加用户
				this.dialogVisible = true
				this.add=true
				
				// 这里调用那个角色列表比较好
				allUser().then(res => {
					console.log('我是规则', res)
					this.ruleForm.type = res.data.data.list
				}).catch(err => {
					console.log('规则失效', err)
				})

			},
			searchUser() {
				// 搜索用户

				this.allAdmin(null, null, this.inpName)
			},
			downLoadExsl(id, title) {
				//数据写入excel
				// 导出
				this.$confirm("此操作将导出列表excel文件, 是否继续?", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						this.excelData = this.tableData; //你要导出的数据list。
						this.export2Excel();
					})
					.catch(() => {});

			},
			export2Excel() {
				var that = this;
				require.ensure([], () => {
					const {
						export_json_to_excel
					} = require("../../excel/Export2Excel"); //这里必须使用绝对路径，根据自己的命名和路径
					const tHeader = [
						// 这个是导出excel里面的表头
						"管理员ID",
						"管理员名称",

					]; // 导出的表头名
					const filterVal = [
						// 这个是你表格数据的字段
						"id",
						"username",
					]; // 导出的表头字段名
					const list = that.excelData;
					// that.excelData为传入的数据
					const data = that.formatJson(filterVal, list);
					export_json_to_excel(tHeader, data, `管理员`); // 导出的表格名称，根据需要自己命名
					// tHeader为导出Excel表头名称，`xxxxxx`即为导出Excel名称
				});
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]));
			},
			handleEdit(index, row) {
				// 编辑用户 
				console.log("编辑用户的scope", row)
				// 触发菜单二
				this.adminId=row.id
				this.title="修改用户"
				this.add=false
				if (this.add==false) {
					this.dialogVisible=true
				} 
				// 这里对数据进行填充
				this.ruleForm.userName=row.username//用户名
				this.imageUrl=row.avatar//头像
				// this.ruleForm.region=row.roleIds//rolsid
				// 这个就是将默认的进行展示
				this.ruleForm.region=row.roleIds
				// 这里调用那个角色列表比较好
				allUser().then(res => {
					// console.log('我是规则', res)
					this.ruleForm.type = res.data.data.list
				}).catch(err => {
					// console.log('规则失效', err)
				})
			},
			handleDelete(index,row) {
				// 删除用户
				console.log("删除用户",row)
				// 进行删除操作
				let params={
					id:row.id,
					username:row.username,
					avatar:row.avatar,
					roleIds:row.roleIds
				}
				delAdmin(params).then(res=>{
					console.log("删除成功！！",res)
					// 调用这个查询的接口
					this.allAdmin()
				}).then(err=>{
					console.log("删除失败",err)
				})
	
			},
			handleSizeChange(val) {
				// 分页改变显示数据
				console.log(`每页 ${val} 条`);
				let params={
					page:this.page,
					limit:val
				}
				adminList(params).then(res=>{
					console.log("每页100条",res)
					this.tableData=res.data.data.list
				}).then(err=>{
					
				})
			},
			handleCurrentChange(val) {
				// 当前页码的数据
				console.log(`当前页: ${val}`);
				let params={
					page:val,
					limit:this.limit
				}
				adminList(params).then(res=>{
					console.log("每页100条",res)
					this.tableData=res.data.data.list
				}).then(err=>{
					
				})
				
				
				
				
			},
			allAdmin(page, limit, username, sort, order) {
				// 管理员列表
				let params = {
					page: page,
					limit: limit,
					username: username
				}
				adminList(params).then(res => {
					// console.log("管理员列表", res)
					this.tableData = res.data.data.list
					// console.log("我是tabledata", this.tableData)
					this.limit = res.data.data.limit
					this.total = res.data.data.total
				}).catch(err => {

				})
			},
			handleAvatarSuccess(res, file) {
				// this.imageUrl = URL.createObjectURL(file.raw);
				console.log("success???", this.imageUrl)
				console.log("我是file", file)
				// 这里将图片地址上传
				this.imageUrl = file.response.data.url
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},
			submitForm(ruleForm) {
				this.dialogVisible = false
				
				if (this.add) {
					// 添加提交
					this.$refs.ruleForm.validate((valid) => {
						// &&this.imageUrl!=''&&this.form.region!=''
						if (valid && this.imageUrl != '' && this.ruleForm.region != '') {
							// 图片进行处理
							let params = {
								username: this.ruleForm.userName,
								password: this.ruleForm.password,
								avatar: this.imageUrl,
								roleIds: this.ruleForm.region
							}
							addAdmin(params).then(res => {
								if (res.data.errno) {
									console.log("管理员名称不符合规定", res)
					
								} else {
									console.log("提交成功yyds", res)
								}
					
							}).then(err => {
								console.log("提交失败", err)
							})
							// 刷新
							this.allAdmin()
							alert('submit!');
						} else {
							console.log('error submit!!');
							console.log('我是选中的', this.ruleForm.region)
							return false;
						}
					});
					
				} else{
					// 添加提交
					this.$refs.ruleForm.validate((valid) => {
						// &&this.imageUrl!=''&&this.form.region!=''
						if (valid && this.imageUrl != '' && this.ruleForm.region != '') {
							// 图片进行处理
							let params = {
								id:this.adminId,
								username: this.ruleForm.userName,
								password: this.ruleForm.password,
								avatar: this.imageUrl,
								roleIds: this.ruleForm.region
							}
							upAdmin(params).then(res => {
									console.log("更新成功yyds", res)				
							}).then(err => {
								console.log("更新失败", err)
							})
							// 刷新
							this.allAdmin()
							alert('submit!');
						} else {
							console.log('error submit!!');
							console.log('我是选中的', this.ruleForm.region)
							return false;
						}
					});
					
					
				}
				
			
			},
			onChange2(file, fileList) {
				this.hideUpload = fileList.length >= this.limitCount;
			},
			handleRemove(file, fileList) {
				this.hideUpload = fileList.length >= this.limitCount;
			},
		},

		mounted() {
			this.allAdmin()
			this.tokens["X-Litemall-Admin-Token"] = this.Cookies.get('token')
			// console.log('token',this.token)
			allUser().then(res => {
				console.log('我是规则2', res)
				this.userList = res.data.data.list
			}).catch(err => {
				console.log('规则失效2', err)
			})
		}
	}
</script>

<style scoped="scoped">
	#role el-table {
		/* 这个就是 */
		text-align: center !important;
	}

	/deep/.el-table__header-wrapper {
		line-height: 50px !important;

	}

	.role-head .el-input {
		width: 200px !important;
		margin-right: 10px;
	}

	.role-head {
		margin-bottom: 15px;
		min-width: 500px;
		overflow: hidden;
	}

	.block {
		margin-top: 20px;
	}

	.ins {
		width: 300px;
	}

	.avator2 {
		width: 40px;
		height: 40px;
	}

	.el-input {
		width: 300px !important;
		margin-right: 10px;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 80px;
		height: 80px;
		line-height: 80px;
		text-align: center;
		border: 1px dashed #CCCCCC;
	}

	.avatar {
		width: 80px;
		height: 80px;
		display: block;
	}

	/deep/.hide .el-upload--picture-card {
		display: none;
	}
</style>
